package com.learn.java3y.java.annotation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class AnnotationTest {

    /**
     * 常规使用: 注解拥有什么属性，在修饰的时候就要给出相对应的值
     *
     * @param username
     * @param age
     */
    @MyAnnotation(username = "张三", age = 20)
    public void add(String username, int age) {
        System.out.println("username: " + username);
        System.out.println("age: " + age);
    }

    @MyAnnotation()
    public void add1(String username, int age) {
        System.out.println("username: " + username);
        System.out.println("age: " + age);
    }

    @MyAnnotation1("zs")
    public void find(String id) {
        System.out.println("id: " + id);
    }

    public static void main(String[] args) {
        try {
            // 反射出该类的方法
            Class clazz = AnnotationTest.class;
            Method addMethod = clazz.getMethod("add", String.class, int.class);
            // 通过方法得到注解上具体的信息
            MyAnnotation myAnnotation = addMethod.getAnnotation(MyAnnotation.class);
            String username = myAnnotation.username();
            int age = myAnnotation.age();
            // 将注解上的信息注入到方法上
            addMethod.invoke(clazz.newInstance(), username, age);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
